package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.managerplus.key.service.KeyGeneratorServicePrx;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 获得全公司适用的模板,可用于发起审批
 * <p>
 * 数据处理思路：根据companyId获取该公司自定义(创建)的模板,这里会包含自带的5个模板
 *
 * @author Administrator
 */
@WebServlet("/getTemplateListFitToWholeCompanyRange")
public class GetTemplateListFitToWholeCompanyRange extends AbstractServlet {
	
	private static final long serialVersionUID = -6524473373623928868L;
	
	private static final Logger logger = LoggerFactory.getLogger(GetTemplateListFitToWholeCompanyRange.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			User user = getReqUser(req);
			
			ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
			
			List<Template> templates = readTemplateServicePrx.getTemplateFitToWholeCompanyRangeList(user);
			
			if (templates == null) {
                List<Template> defaultTemplates = readTemplateServicePrx.getDefaultTemplateToInit(user);
                KeyGeneratorServicePrx keyGeneratorService = ServantUtils.getObject(KeyGeneratorServicePrx.class);
                List<Integer> dbKeyss = keyGeneratorService.generateKeys("requestTemplate", defaultTemplates.size());

                for (int i = 0; i < defaultTemplates.size(); i++) {
					Template template = defaultTemplates.get(i);
                    template.setTemplateId(dbKeyss.get(i));
					defaultTemplates.set(i, template);
				}
				readTemplateServicePrx.initMyCompanysTemplateList(user, defaultTemplates);
				templates = readTemplateServicePrx.getTemplateFitToWholeCompanyRangeList(user);
			}
			
			returnResult(resp, templates);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}
	
	private void returnResult(HttpServletResponse resp, List<Template> templates) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "获得成功");
		jsonObject.put("item", templates);
		
		logger.info(jsonObject.toJSONString());
		
		printJson(resp, jsonObject.toJSONString());
	}
	
}
